#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""
Created on 2022年7月1日
@author: ycs
@description: 向一个QWidget中嵌入一个外部window。输入一个Widget。 一个三方程序的运行路径。启动应用，获取窗口句柄
"""

import sys
import subprocess
import time

import win32con
import win32gui
from loguru import logger

from PyQt5.QtGui import QWindow
from PyQt5.QtWidgets import QWidget, QVBoxLayout, QLayout
from PyQt5.QtCore import Qt


class EmbedWindow(object):

    def __init__(self, qtWidgets:QWidget):
        super().__init__()
        self.parentWidgets = qtWidgets


    def startProcessAndEmbedWindow(self, exePath, className, windowName):
        self.thirdPartyPath = exePath

        import threading
        t = threading.Thread( target = self.runExe, args=(self.thirdPartyPath,))
        t.start()

        return self.embedExistingWindow(className, windowName)
    
    def embedExistingWindow(self, className, windowName):

        hwnd = win32gui.FindWindow(className, windowName)

        start = time.time()
        while hwnd == 0:
            time.sleep(0.01)
            hwnd = win32gui.FindWindow(className, windowName)
            end = time.time()
            if end - start > 5:
                logger.warning("cannot find the window from the classname:{}, windowName:{}.", className, windowName)
                return

        # 嵌入之前的属性
        style = win32gui.GetWindowLong(hwnd, win32con.GWL_STYLE)
        exstyle = win32gui.GetWindowLong(hwnd, win32con.GWL_EXSTYLE)
        wrect = win32gui.GetWindowRect(hwnd)[:2] + win32gui.GetClientRect(hwnd)[2:]

        widget = QWidget.createWindowContainer(QWindow.fromWinId(hwnd))
        widget.hwnd = int(hwnd)  # 窗口句柄
        widget.phwnd = int(self.parentWidgets.winId())  # 父窗口句柄
        widget.style = style  # 窗口样式
        widget.exstyle = exstyle  # 窗口额外样式
        widget.wrect = wrect  # 窗口位置

        widget.setWindowFlags(Qt.WindowStaysOnTopHint | Qt.FramelessWindowHint)
        win32gui.SetParent(int(widget.hwnd), int(self.parentWidgets.winId()))
        win32gui.SetWindowPos(int(widget.hwnd),0, 0, 0, 0, 0, win32con.SWP_NOSIZE )
        logger.debug("embed the window with window name: {} successfully.", windowName)

        return widget

    def show(self):
        if self.parentWidgets is not None:
            self.parentWidgets.show()

    @staticmethod
    def runExe( exePath ):
        #TODO 判断是不是exe可执行程序
        subprocess.Popen(exePath)

if __name__ == '__main__':

    import simpleplot

    from PyQt5.QtWidgets import QWidget, QApplication

    app = QApplication(sys.argv)
    widget = QWidget()
    widget.setWindowTitle("EmbedWindow")
    layout = QVBoxLayout()
    widget.setLayout(layout)
    widget.setGeometry(50, 50, 500, 500)

    exePath = "C:\\Windows\\System32\\Taskmgr.exe"
    embedWindow = EmbedWindow(widget)

    #childwidget = embedWindow.startProcessAndEmbedWindow(exePath, "TaskManagerWindow", "Task Manager")
    simpleplt = simpleplot.initialize()
    title = simpleplt.simpleplot(float(10))
    childwidget = embedWindow.embedExistingWindow("SunAwtFrame", "Figure 1")

    widget.layout().addWidget(childwidget)


    embedWindow.show()
    time.sleep(30)
    sys.exit(app.exec_())